<template>
	<view class="homePage" :dataInfo="dataInfo" :change:dataInfo="ether.getdataInfo">
		<view class="header" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="left">
				<view class="nav">
					<image src="/static/images/home/nav.png" mode="widthFix" class="icon" @tap="open"></image>
				</view>
				<view class="states">
					<view :class="['block', state]" class="block" @click="setRpc"></view>
				</view>
			</view>
			<!-- 	<view class="right">
				<view class="add">
					<image src="/static/images/home/add.png" mode="widthFix" class="icon"></image>
				</view>
				<view class="san" @tap="startScan">
					<image src="/static/images/home/san.png" mode="widthFix" class="icon"></image>
				</view>
			</view> -->
		</view>
		<view class="headempty"></view>
		<view class="contentBox">
			<view class="refresh-control" v-if="isPullingDown || isRefreshing" :style="{height: distance+ 'px'}">
				<text>{{ refreshText }}</text>
			</view>
			<scroll-view scroll-y="true" class="" v-if="choinInfo && choinInfo.length>0" @touchstart="onTouchStart"
				@touchmove="onTouchMove" @touchend="onTouchEnd">
				<view class="wallet_cell">
					<view class="wallet" :style="chainStyles">
						<view class="title">
							<view class="left">
								<view class="name">
									{{addressInfo?.name}}
								</view>
								<!-- <view class="look">
								<image src="/static/images/home/look.png" mode="widthFix" class="icon"></image>
							</view> -->
							</view>
							<view class="right" @tap="wallectDetail">
								<view class="detail">
									详情
								</view>
								<view class="r_icon">
									<image src="../../static/images/home/right.png" mode="" class="icon"></image>
								</view>
							</view>
						</view>
						<view class="balance">
							<text class="symbol">$</text>
							<text class="total">{{$utils.toTwoDecimalDown(balance)}}</text>
						</view>
					</view>
					<!-- 	<view class="nav_box">
					<view class="nav" @tap="transfer">
						<view class="icon_box">
							<image src="/static/images/home/transfer.png" mode="widthFix" class="icon"></image>
						</view>
						<view class="text">
							转账
						</view>
					</view>
					<view class="line"></view>
					<view class="nav" @tap="addqrcode">
						<view class="icon_box">
							<image src="/static/images/home/receive.png" mode="widthFix" class="icon"></image>
						</view>
						<view class="text">
							收款
						</view>
					</view>
					<view class="line"></view>
					<view class="nav">
						<view class="icon_box">
							<image src="/static/images/home/buy.png" mode="widthFix" class="icon"></image>
						</view>
						<view class="text">
							授权
						</view>
					</view>
					<view class="line"></view>
					<view class="nav" @tap="broswer">
						<view class="icon_box">
							<image src="/static/images/home/exchange.png" mode="widthFix" class="icon"></image>
						</view>
						<view class="text">
							浏览器
						</view>
					</view>
				</view> -->
				</view>

				<view class="menu" v-if="Appstatus==0">
					<view class="item" @tap="transfer">
						<image src="/static/images/home/menu1.png" mode="widthFix" class="icon"></image>
						<view class="text">
							转账
						</view>
					</view>
					<view class="item" @tap="addqrcode">
						<image src="/static/images/home/menu2.png" mode="widthFix" class="icon"></image>
						<view class="text">
							收款
						</view>
					</view>
					<view class="item" @tap="approve()">
						<image src="/static/images/home/menu3.png" mode="widthFix" class="icon"></image>
						<view class="text">
							授权检测
						</view>
					</view>
					<view class="item" @tap="webView(2)">
						<image src="/static/images/home/menu4.png" mode="widthFix" class="icon"></image>
						<view class="text">
							区块浏览器
						</view>
					</view>
				</view>
				<view class="scroll">
					<view class="scroll_title">
						<view class="title">
							资产
						</view>
						<view class="right">
							<!-- <view class="search">
							<image src="/static/images/home/search.png" mode="widthFix" class="icon"></image>
							<view class="text">
								<input class="ipt" type="text" placeholder="搜索" placeholder-class="place"
									@input="clearInput" :value="inputClearValue" />
								<text class="iconfont icon-close" v-if="showClearIcon" @click="clearIcon"></text>
							</view>
						</view> -->
							<view class="add" @tap="addCoin">
								<image src="/static/images/home/coinadd.png" mode="widthFix" class="icon"></image>
							</view>
						</view>
					</view>
					<view class="scroll-Y">
						<uni-swipe-action>
							<uni-swipe-action-item :disabled="item.tokenaddress==$config.defaultAddress"
								:right-options="options" v-for="(item,index) in choinInfo" :key="index">
								<template v-slot:right>
									<view class="del" @tap="bindClick(item)"><text>删除</text></view>
								</template>
								<view class="scroll-view-item" @tap="coinDetial(item)">
									<view class="coin">
										<image
											:src="'/static/images/tokenicon/' +item.tokenaddress+item.chainType+item.chainId+'.png'"
											mode="widthFix" class="icon" @error="imageError(item)" v-if="!item.err">
										</image>
										<image src="/static/images/notoken.png" mode="widthFix" class="icon"
											v-show="item.err"></image>
									</view>
									<view class="coin_describe">
										<view class="left">
											<view class="name">
												{{item.tokensymbol}}
											</view>
										</view>
										<view class="right">
											<view class="total">
												{{$utils.toTwoDecimalDown(item.tokennum,4)}}
											</view>
											<view class="total_u">
												≈
												${{$utils.toTwoDecimalDown($utils.formatNumber(item.tokenprice * item.tokennum),2)}}
											</view>
										</view>
									</view>
								</view>
							</uni-swipe-action-item>
						</uni-swipe-action>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "homePage",
		computed: {
			address() {
				return this.$store.getters.getAddress;
			},
			chainId() {
				return this.$store.getters.getChainId;
			},
			addressInfo() {
				return this.$store.getters.addressInfo
			},
			choinInfo() {
				return this.$store.getters.choinInfo
			},
			Appstatus() {
				return this.$store.getters.Appstatus
			},
			chainInfo() {
				return this.$store.getters.chainInfo
			},
			chainStyles() {
				return {
					backgroundColor: this.chainInfo?.wallteColor,
					backgroundImage: `url(/static/images/chain/${this.chainInfo?.chainName}bg.png)`
				}
			},
			balance() {
				const totalValue = this.choinInfo?.reduce((sum, token) => {
					return sum + (parseFloat(token.tokennum) * parseFloat(token.tokenprice));
				}, 0);
				return totalValue || 0
			},
			dataInfo() {
				return {
					rpc: this.$store.getters.getRpc,
					chainType: this.addressInfo?.chainType,
					timeId: this.timeId
				}
			},
		},
		data() {
			return {
				inputClearValue: "",
				showClearIcon: false,
				statusBarHeight: 0,
				distance: 0,
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#F56C6C'
					}
				}],
				state: "state1",
				startY: 0, // 手指触摸起始位置
				isPullingDown: false, // 是否正在下拉中
				isRefreshing: false, // 是否正在刷新中
				refreshText: "下拉刷新", // 下拉刷新状态提示文本
				timeId: Date.now(),
				interval: null,
			};
		},
		created() {
			uni.getSystemInfo({
				success: (res) => {
					this.statusBarHeight = res?.statusBarHeight; // 设置状态栏高度
				}
			});
		},
		mounted() {
			this.timeId = Date.now()
			if (!this.interval) {
				this.interval = setInterval(() => {
					this.timeId = Date.now()
				}, 60000)
			}
		},
		methods: {
			imageError(item) {
				this.$set(item, 'err', true);
			},
			// 手指触摸开始
			onTouchStart(event) {
				this.startY = event.touches[0].pageY; // 获取初始触摸位置
			},
			// 手指滑动
			onTouchMove(event) {
				const moveY = event.touches[0].pageY;
				const distance = moveY - this.startY; // 计算下拉距离
				this.distance = distance
				// 如果距离大于50px，展示"释放刷新"，否则展示"下拉刷新"
				if (distance > 50 && !this.isRefreshing) {
					this.isPullingDown = true;
					this.refreshText = "释放刷新";
				} else if (distance > 0 && !this.isRefreshing) {
					this.isPullingDown = true;
					this.refreshText = "下拉刷新";
				} else {
					this.isPullingDown = false;
				}
			},
			// 手指离开屏幕
			onTouchEnd() {
				if (this.refreshText === "释放刷新" && !this.isRefreshing) {
					this.triggerRefresh(); // 触发刷新
				} else {
					this.isPullingDown = false;
				}
			}, // 触发刷新
			triggerRefresh() {
				this.timeId = Date.now()
				this.isRefreshing = true;
				this.refreshText = "正在刷新...";
				this.$updateWalletInfo().then(res => {
					setTimeout(() => {
						this.isRefreshing = false;
						this.isPullingDown = false;
						this.refreshText = "下拉刷新";
					}, 1500)

				})
			},
			getRpcState(state) {
				this.state = state
			},
			approve() {
				if (this.addressInfo?.importMethod == 4) {
					return uni.showToast({
						title: "观察钱包没有操作权限",
						position: "bottom",
						icon: 'none'
					});
				}
				if (this.chainId == 0) {
					uni.navigateTo({
						url: '/pages/approve/approve'
					})
				} else if (this.chainId == 56) {
					uni.navigateTo({
						url: '/pages/approveDetail/approveDetail'
					})
				} else if (this.chainId == 5867) {
					uni.navigateTo({
						url: '/pages/ethApprove/ethApprove'
					})
				}

			},
			webView(type) {
				if (type == 1) {
					if (this.chainInfo?.chainType == "TRON") {
						uni.navigateTo({
							url: `/pages/webView/webView?url=https://approval.tptool.pro/#/?address=${this.address}&chain_id=728126428&title=授权检测`
						})
					} else {
						if (this.chainInfo?.mainCoinName == 'JUMP') {
							return uni.showToast({
								title: "暂未开放",
								position: "bottom",
								icon: "none",
								duration: 2000
							});
						}
						uni.navigateTo({
							url: `/pages/webView/webView?url=https://approval.tptool.pro/#/?address=${this.address}&chain_id=56&title=授权检测`
						})
					}
				} else {
					uni.navigateTo({
						url: `/pages/webView/webView?url=${this.chainInfo.browser}&title=区块浏览器`
					})
				}
			},
			open() {
				this.$emit('showPopup');
			},
			bindClick(item) {
				this.delToken(item.tokenaddress)
			},
			//删除代币
			delToken(tokenAddress) {
				uni.$db.delete('list', { // 删除一条数据
					from: 'choinList',
					where: [{
						address: `= "${this.address}"`,
						chainId: `= "${this.chainId}"`,
						tokenaddress: `= "${tokenAddress}"`
					}]
				}).then(res => {
					this.$updateWalletInfo()
				})
			},
			clearInput(event) {
				this.inputClearValue = event.detail.value;
				if (event.detail.value.length > 0) {
					this.showClearIcon = true;
				} else {
					this.showClearIcon = false;
				}
			},
			clearIcon() {
				this.inputClearValue = '';
				this.showClearIcon = false;
			},
			wallectDetail() {
				uni.navigateTo({
					url: '/pages/wallectDetail/wallectDetail'
				})
			},
			setRpc() {
				uni.navigateTo({
					url: '/pages/rpc/rpc'
				})
			},
			coinDetial(item) {
				const conInfoStr = encodeURIComponent(JSON.stringify(item));
				uni.navigateTo({
					url: `/pages/coinDetial/coinDetial?conInfoStr=${conInfoStr}`
				})
			},
			addqrcode() {
				if (this.addressInfo.importMethod != 4) {
					uni.navigateTo({
						url: `/pages/addressQRcode/addressQRcode`
					})
				} else {
					uni.showToast({
						title: "观察钱包没有操作权限",
						position: "bottom",
						icon: 'none'
					});
				}

			},
			addCoin() {
				uni.navigateTo({
					url: '/pages/addCoin/addCoin'
				})
			},
			broswer() {
				uni.switchTab({
					url: '/pages/broswer/broswer', // 这里的路径是 tabBar 页面在项目中的路径
					success() {},
					fail(err) {}
				});
			},
			transfer() {
				if (this.addressInfo.importMethod != 4) {
					uni.navigateTo({
						url: '/pages/transfer/transfer'
					})
				} else {
					uni.showToast({
						title: "观察钱包没有操作权限",
						position: "bottom",
						icon: 'none'
					});
				}
			},
		}
	}
</script>

<script module="ether" lang="renderjs">
	export default {
		data() {
			return {
				jsLoadState: false,
				tjsLoadState: false,
				dataLoadState: false,
				dataInfo: {},
			}
		},
		mounted() {
			const ethersScript = document.createElement('script');
			ethersScript.src = 'static/script/ethers-5.2.umd.min.js';
			ethersScript.onload = async () => {
				this.jsLoadState = true;
				if (this.dataLoadState) {
					this.getBlockHeight()
				}
			};
			document.head.appendChild(ethersScript);
			// 载入 TronWeb.js
			const tronWebScript = document.createElement('script');
			tronWebScript.src = 'static/script/newTronWeb.js';
			tronWebScript.onload = () => {
				this.tjsLoadState = true;
				if (this.dataLoadState) {
					this.getBlockHeight()
				}
			};
			document.head.appendChild(tronWebScript);
		},
		methods: {
			//同步数据
			async getdataInfo(newValue) {
				if (JSON.stringify(this.dataInfo) === JSON.stringify(newValue)) return;
				this.dataInfo = newValue
				this.dataLoadState = true
				this.getBlockHeight()
			},
			async getBlockHeight() {
				if (this.dataInfo?.chainType == 'ETH' && this.jsLoadState) {
					let provider = new ethers.providers.JsonRpcProvider(this.dataInfo.rpc);
					let state = 'state3'
					try {
						const start = Date.now();
						let block = await provider.getBlockNumber()
						const ping = Date.now() - start;
						if (ping < 300) {
							state = 'state1'; // 绿色
						} else if (ping <= 500) {
							state = 'state2'; // 黄色
						} else {
							state = 'state3'; // 红色
						}
					} catch (e) {
						state = 'state3'; // 红色
					}
					this.$ownerInstance.callMethod('getRpcState', state);
				} else if (this.dataInfo?.chainType == 'TRON' && this.tjsLoadState) {
					const tronWeb = new TronWeb.TronWeb({
						fullHost: this.dataInfo.rpc,
					});
					let state = 'state3'
					try {
						const start = Date.now();
						const block = await tronWeb.trx.getCurrentBlock();
						const ping = Date.now() - start;
						if (ping < 300) {
							state = 'state1'; // 绿色
						} else if (ping <= 500) {
							state = 'state2'; // 黄色
						} else {
							state = 'state3'; // 红色
						}
					} catch (error) {
						state = 'state3'; // 红色
					}
					this.$ownerInstance.callMethod('getRpcState', state);
				}
			}
		},
	}
</script>
<style lang="scss">
	@import "/static/iconfont/iconfont.css";

	.homePage {
		width: 100%;
		height: 100%;

		.headempty {
			width: 100%;
			margin-top: 80upx;
		}

		.header {
			width: 100%;
			height: 80upx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			position: fixed;
			left: 0;
			top: 0;
			z-index: 99;
			background-color: #FFF;

			.left {
				display: flex;
				align-items: center;
				margin-left: 54upx;

				.nav {
					display: flex;

					.icon {
						width: 44upx;
						height: 44upx;
					}
				}

				.states {
					margin-left: 18upx;
					display: flex;

					.block {
						width: 18upx;
						height: 18upx;
						border-radius: 9upx;
					}

					.state1 {
						background: #368321;
					}

					.state2 {
						background: #F9B909;
					}

					.state3 {
						background: #D73C3C;
					}
				}
			}

			.right {
				display: flex;
				align-items: center;
				margin-right: 38upx;

				.add {
					display: flex;
					margin-right: 18upx;

					.icon {
						width: 44upx;
						height: 44upx;
					}
				}

				.san {
					display: flex;

					.icon {
						width: 44upx;
						height: 44upx;
					}
				}
			}
		}

		.contentBox {
			width: 100%;

			.refresh-control {
				width: 100%;
				max-height: 100upx;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 20upx;
				color: #A2A2A2;
			}

			.wallet_cell {
				box-shadow: 0px 0px 10px 0px rgba(216, 216, 216, 0.6);
				border-radius: 20upx;
				margin: 0 30upx;

				.wallet {
					width: 100%;
					height: 202upx;
					border-radius: 20upx;
					box-sizing: border-box;
					padding: 0 32upx 0 44upx;
					background-size: 100% 100%;
					background-repeat: no-repeat;

					.title {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 26upx 0;
						color: #FFFFFF;
						font-size: 26upx;
						font-weight: 500;

						.left {
							display: flex;
							align-items: center;

							.name {
								margin-right: 8upx;
							}

							.look {
								display: flex;

								.icon {
									width: 32upx;
									height: 32upx;
								}
							}
						}

						.right {
							display: flex;
							align-items: center;

							.detail {
								margin-right: 12upx;
							}

							.r_icon {
								display: flex;

								.icon {
									width: 22upx;
									height: 22upx;
								}
							}
						}

					}
				}

				.balance {
					height: 100upx;
					display: flex;
					font-size: 36upx;
					font-weight: 500;
					color: #FFFFFF;
					display: flex;
					align-items: end;

					.total {
						line-height: 70upx;
					}

					.symbol {
						line-height: 70upx;
						font-size: 26upx;
						margin-right: 4upx;
					}
				}
			}

			.nav_box {
				width: 100%;
				height: 100upx;
				box-sizing: border-box;
				padding: 0 58upx;
				display: flex;
				justify-content: space-between;
				color: #3D3D3D;
				font-weight: 400;
				font-size: 28upx;
				align-items: center;

				.line {
					width: 1px;
					height: 22upx;
					background: #D8D8D8;
				}

				.nav {
					display: flex;
					align-items: center;

					.icon_box {
						display: flex;
						margin-right: 16upx;

						.icon {
							width: 32upx;
							height: 32upx;
						}
					}
				}

			}

			.menu {
				margin: 0 30upx;
				border: 1px solid #D8D8D8;
				border-radius: 20upx;
				font-size: 24upx;
				color: #3D3D3D;
				display: flex;
				justify-content: space-around;
				margin-top: 50upx;

				.item {
					display: flex;
					flex-direction: column;
					align-items: center;
					padding: 26upx 0 18upx;

					.icon {
						width: 46upx;
						height: 46upx;
						margin-bottom: 10upx;
					}

				}
			}

			.scroll {
				.scroll_title {
					display: flex;
					justify-content: space-between;
					padding: 36upx 30upx 0;

					.title {
						font-size: 32upx;
						color: #3D3D3D;
						font-weight: bold;
					}

					.right {
						display: flex;

						.search {
							display: flex;
							background: #F5F6F8;
							margin-right: 20upx;
							align-items: center;
							width: 164upx;
							height: 46upx;
							border-radius: 23upx;
							padding-left: 10upx;
							padding-right: 10upx;
							box-sizing: border-box;

							.text {
								font-size: 24upx;
								color: #3D3D3D;
								display: flex;
								align-items: center;

								.ipt {
									flex: 1;
									height: 46upx;
									color: red;
									font-size: 24upx;
									margin: 0 10upx;

									.place {
										color: #A2A2A2;
										font-size: 24upx;
									}
								}

							}

							.icon {
								width: 100upx;
								height: 100upx;
							}
						}

						.add {
							width: 46upx;
							height: 46upx;
							border-radius: 23upx;
							background-color: #F5F6F8;
							display: flex;
							justify-content: center;
							align-items: center;

							.icon {
								width: 32upx;
								height: 32upx;
							}
						}
					}
				}

				.scroll-Y {
					width: 100%;
					padding-left: 30upx;
					box-sizing: border-box;

					.del {
						font-size: 28upx;
						height: 100%;
						display: flex;
						align-items: center;
						padding: 0 50upx;
						background: #F56C6C;
						color: #FFFFFF;
					}

					.scroll-view-item {
						display: flex;
						padding-top: 40upx;

						.coin {
							display: flex;
							margin-right: 14upx;

							.icon {
								width: 72upx;
								height: 72upx;
								border-radius: 50%
							}
						}

						.coin_describe {
							flex: 1;
							border-bottom: 1px solid #D8D8D8;
							display: flex;
							align-items: center;
							justify-content: space-between;
							padding: 0 40upx 32upx 8upx;
							color: #3D3D3D;
							font-weight: 400;

							.left {
								display: flex;
								flex-direction: column;

								.name {
									font-size: 36upx;
								}

								.price {
									color: #A2A2A2;
									font-size: 24upx;
								}
							}

							.right {
								display: flex;
								flex-direction: column;
								align-items: end;

								.total {
									font-size: 36upx;
								}

								.total_u {
									color: #A2A2A2;
									font-size: 24upx;
								}
							}
						}
					}
				}
			}
		}
	}
</style>